const BaseController = require("./base");
const NotFoundException = require("../exception/not_found");

function toInt(str) {
  if (typeof str === "number") return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class WordController extends BaseController {

  async getUserWordCount() {
    const { ctx, app } = this;
    const data = await ctx.service.word.getUserWordCount();
    this.success(data);
  }

  async getWordCount() {
    const { ctx, app } = this;
    const data = await ctx.service.word.getWordCount();
    this.success(data);
  }

  async getLearnedWordCount() {
    const { ctx, app } = this;
    const data = await ctx.service.word.getLearnedWordCount();
    this.success(data);
  }

  async getUnlearnedWords() {
    const { ctx, app } = this;
    const data = await ctx.service.word.getUnlearnedWords();
    this.success(data);
  }

  async getUnReviewWords() {
    const { ctx, app } = this;
    const data = await ctx.service.word.getUnReviewWords();
    this.success(data);
  }

  async getWordsList() {
    const { ctx, app } = this;
    const data = await ctx.service.word.getWordsList(ctx.request.body);
    this.success(data);
  }

  async updateWord() {
    const { ctx, app } = this;
    const data = await ctx.service.word.updateWord(ctx.request.body);
    if (data) {
      this.success(data);
    } else {
      this.fail('编辑失败')
    }
  }
  async deleteWord() {
    const { ctx, app } = this;
    const { id } = ctx.request.body;
    if (!id) {
      this.fail('删除失败')
    }
    try {
      // 检查单词是否存在
      const word = await ctx.model.Word.findByPk(id);
      if (!word) {
        this.fail('单词不存在')
      }
      const deleted = await ctx.model.Word.destroy({ where: { id } });
  
      if (deleted > 0) {
        this.success('单词删除成功');
      } else {
        this.fail('删除失败')
      }
    } catch (error) {
      this.fail('删除失败')
    }
  }

}

module.exports = WordController;
